package com.ma;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @ClassName TestProxy
 * @Author: mayongqiang
 * @DATE 2022/4/10 17:10
 * @Description:
 */
public class TestProxy {
    public static void main(String[] args) throws Exception {

        byte[] dump = $Proxy0Dump.dump();
        /*
           将字节码写到一个.class文件中  反编译即为初始的 $Proxy0.java
         */
        //FileOutputStream os = new FileOutputStream("$Proxy0.class");
        //os.write(dump,0,dump.length);
        //os.close();

        /*
           直接在内存中加载使用该二进制字节码
         */
        ClassLoader loader = new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                return super.defineClass(name, dump, 0, dump.length);
            }
        };
        Class<?> proxyClass = loader.loadClass("com.ma.$Proxy0");

        Constructor<?> constructor = proxyClass.getDeclaredConstructor(InvocationHandler.class);
        constructor.setAccessible(true);
        Foo proxy = (Foo) constructor.newInstance(new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("before");
                System.out.println("target");
                return null;
            }
        });
        proxy.foo();


    }
}
